package cn.zlj.nmcc.service.impl;

import cn.zlj.nmcc.constants.BaseConstants;
import cn.zlj.nmcc.domain.CourseType;
import cn.zlj.nmcc.mapper.CourseTypeMapper;
import cn.zlj.nmcc.service.ICourseTypeService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程目录 服务实现类
 * </p>
 *
 * @author zlj
 * @since 2022-11-21
 */
@Service
public class CourseTypeServiceImpl extends ServiceImpl<CourseTypeMapper, CourseType> implements ICourseTypeService {

    @Override
    @Cacheable(cacheNames = BaseConstants.CourseRedisTreeData.COURSE_REDIS_TREE_DATA,key = BaseConstants.CourseRedisTreeData.COURSE_REDIS_TREE_DATA_KEY)
    public List<CourseType> treeData() {

        return getCourseTypes();
    }

    private List<CourseType> getCourseTypes() {
        List<CourseType> courseTypes = super.selectList(null);
        Map<Long, CourseType> map = courseTypes.stream().collect(Collectors.toMap(CourseType::getId, ty -> ty));
        List<CourseType> result =new ArrayList<>();
        courseTypes.forEach(courseType -> {
            if (courseType.getPid()!=null&&courseType.getPid()==0L){
                result.add(courseType);
            }
            else {
                CourseType courseTy = map.get(courseType.getPid());
                if(courseTy!=null){
                    courseTy.getChildren().add(courseType);
                }
            }
        });
        return result;
    }

    @Override
    @CacheEvict(cacheNames = BaseConstants.CourseRedisTreeData.COURSE_REDIS_TREE_DATA,key = BaseConstants.CourseRedisTreeData.COURSE_REDIS_TREE_DATA_KEY)
    public boolean insert(CourseType entity) {
        return super.insert(entity);
    }

    @Override
    @CacheEvict(cacheNames = BaseConstants.CourseRedisTreeData.COURSE_REDIS_TREE_DATA,key = BaseConstants.CourseRedisTreeData.COURSE_REDIS_TREE_DATA_KEY)
    public boolean deleteById(Serializable id) {
        return super.deleteById(id);
    }

    @Override
    @CacheEvict(cacheNames = BaseConstants.CourseRedisTreeData.COURSE_REDIS_TREE_DATA,key = BaseConstants.CourseRedisTreeData.COURSE_REDIS_TREE_DATA_KEY)
    public boolean updateById(CourseType entity) {
        return super.updateById(entity);
    }
}
